package registnet.cpm;


import java.util.List;

import registnet.base.IChecklist;
import registnet.base.ICourse;
import registnet.base.Prerequisite;

/**
 * Defines a class for creating a <code>Project</code> from a checklist.
 */
public class ProjectSource {

	/**
	 * The checklist that will be converted to the project.
	 */
	private IChecklist checklist;
	
	/**
	 * The resulting project created from the checklist.
	 */
	private Project project;
	
	/**
	 * Creates a project with the given project name from the given checklist.
	 * @param projectName
	 * @param checklist
	 */
	public ProjectSource(String projectName, IChecklist checklist){
		project = new Project(projectName);
		this.checklist = checklist;
		load();
	}
	
	/**
	 * Loads the data from the checklist and converts it to a project.
	 */
	public void load(){
		//create nodes
		List<ICourse> coursesToTake = this.checklist.getAllCoursesToTake();
		for(int i=0; i<coursesToTake.size(); i++){
			Node node = new Node(coursesToTake.get(i).getCourseCode().toString(),1);
			this.project.addNode(node);
		}
		
		//create arcs
		for(int i=0; i<coursesToTake.size(); i++){
			ICourse course = coursesToTake.get(i);
			List<Prerequisite> prerequisites = course.getPrerequisites();
			if(prerequisites.size()==1 && prerequisites.get(0).getDescription().equals("NONE"))
				continue;
			for(int j=0; j<prerequisites.size(); j++){
				String[] tokens = prerequisites.get(j).getDescription().split(" AND ");
				for(int k=0; k<tokens.length; k++){
					if(this.project.hasNode(tokens[k])){
						Arc arc = new Arc();
						arc.setStartNode(project.getNode(tokens[k]));
						arc.setEndNode(project.getNode(course.getCourseCode()));
						arc.setName(arc.getStartNode().getName() + "-" + arc.getEndNode().getName());
						project.addArc(arc);
					}
				}
			}
			
		}
	}
	
	/**
	 * Returns the project.
	 * @return the project
	 */
	public Project getProject(){
		return this.project;
	}
	
}
